package public

import (
	"encoding/json"
	"fmt"
	"gin/app/http/global"
	area2 "gin/app/http/model/area"
	"gin/app/http/struct/area"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
)

func GetArea(c *gin.Context) {
	rawBody, _ := ioutil.ReadAll(c.Request.Body)
	var params area.GetAreaParam
	err := json.Unmarshal(rawBody, &params)
	if err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	var arr []area2.Area
	var DB = global.DB
	//result := DB.Where("parent_id = ?", params.ParentId).Find(&arr)
	result := DB.Find(&arr)

	if result.Error != nil {
		fmt.Println("Failed:", result.Error)
	}
	// 将 arr 转换为 []map[string]interface{}
	var arrAsMap []map[string]interface{}
	for _, a := range arr {
		arrAsMap = append(arrAsMap, map[string]interface{}{
			"id":        a.Id,
			"name":      a.Name,
			"parent_id": a.ParentId,
			"type":      a.Type,
		})
	}
	newArr := buildTree(arrAsMap)
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"msg":  "请求成功!",
		"data": newArr,
	})
}

type TreeNode struct {
	ID       int         `json:"id"`
	Name     string      `json:"name"`
	Type     int         `json:"type"`
	Children []*TreeNode `json:"children"`
}

func buildTree(data []map[string]interface{}) *TreeNode {
	nodes := make(map[int]*TreeNode)
	var root *TreeNode

	for _, item := range data {
		id := item["id"].(int)
		name := item["name"].(string)
		parentID := item["parent_id"].(int)
		node := &TreeNode{ID: id, Name: name, Type: item["type"].(int)}
		nodes[id] = node

		if parentID == 0 {
			root = node
		} else {
			parent := nodes[parentID]
			parent.Children = append(parent.Children, node)
		}
	}

	return root
}

func PrintTree(node *TreeNode, depth int) {
	fmt.Printf("%s- %s\n", getIndent(depth), node.Name)
	for _, child := range node.Children {
		PrintTree(child, depth+1)
	}
}

func getIndent(depth int) string {
	const indentStr = "    " // 4个空格
	indent := ""
	for i := 0; i < depth; i++ {
		indent += indentStr
	}
	return indent
}
